<template>
    <div class="page-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="一级销区" prop="qyyxAcXq1">
                        <el-select
                            v-model="form.qyyxAcXq1"
                            placeholder="请选择"
                            @change="onChangeXq1"
                        >
                            <el-option
                                v-for="dict in xq1Options"
                                :key="dict.RP02"
                                :label="dict.RP02NAME"
                                :value="dict.RP02"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="二级销区" prop="qyyxAcXq2">
                        <el-select
                            v-model="form.qyyxAcXq2"
                            placeholder="请选择"
                            @change="onChangeXq2"
                        >
                            <el-option
                                v-for="dict in xq2Options"
                                :key="dict.RP03"
                                :label="dict.RP03NAME"
                                :value="dict.RP03"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="品牌" prop="qyyxAcPp">
                        <el-select
                            v-model="form.qyyxAcPp"
                            placeholder="请选择"
                            @change="onChangeBrand"
                            clearable
                        >
                            <el-option
                                v-for="dict in brandOptions"
                                :key="dict.BRAND_CODE"
                                :label="dict.BRAND_NAME"
                                :value="dict.BRAND_CODE"
                            ></el-option>
                        </el-select>
                    </el-form-item> 
                </el-col>
            </el-row>
            <el-row v-if="form.qyyxAcXq1&&form.qyyxAcXq2&&!form.qyyxAcPp">
                <el-col :span="8">
                    <el-form-item label="默认活动" prop="lzjbYl2">
                        <el-select
                            v-model="form.lzjbYl2"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="dict in activityTypeOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="活动开始时间" prop="qyyxAcStart">
                        <el-date-picker clearable
                            v-model="form.qyyxAcStart"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="活动结束时间" prop="qyyxAcEnd">
                        <el-date-picker clearable 
                            v-model="form.qyyxAcEnd"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="活动标题" prop="qyyxAcName">
                        <el-input v-model="form.qyyxAcName" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row>
                <!-- <el-col :span="8">
                    <el-form-item label="获客奖励" prop="qyyxAcHk">
                        <el-input type="number" v-model="form.qyyxAcHk" placeholder="请输入" style="width:300px; display: inline-block;"/>
                        <el-select v-model="form.qyyxAcHkType" placeholder="请选择" style="width:100px; display: inline-block;">
                            <el-option
                                v-for="dict in jlOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="成交奖励" prop="qyyxAcCj">
                        <el-input type="number" v-model="form.qyyxAcCj" placeholder="请输入" style="width:300px; display: inline-block;"/>
                        <el-select v-model="form.qyyxAcCjType" placeholder="请选择" style="width:100px; display: inline-block;">
                            <el-option
                                v-for="dict in jlOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="8">
                    <el-form-item label="活动客服" prop="qyyxAcKf">
                        <el-input v-model="form.qyyxAcKf" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row v-if="form.qyyxAcHkType=='1'||form.qyyxAcCj=='1'">
                <el-col :span="8">
                    <el-form-item label="MCU" prop="lzjbYl1">
                        <el-input v-model="form.lzjbYl1" placeholder="请输入"/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="活动海报" prop="qyyxAcPosterImg">
                        <div>（导出后贴二维码，1501*2667）</div>
                        <!-- <el-input v-model="form.qyyxAcPosterImg" placeholder="请输入活动头图" /> -->
                        <el-upload :action="posterImgAction" :headers="uploadHeaders" :file-list="posterImg" list-type="picture-card" :on-success="handleUploadSuccPoster">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                        <i class="el-icon-zoom-in"></i>
                                    </span>
                                    <span class="el-upload-list__item-delete" @click="handlePicRemove(file, posterImg)">
                                        <i class="el-icon-delete"></i>
                                    </span>
                                </span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row>
                <el-col :span="24">
                    <el-form-item label="分享图片" prop="qyyxAcShareImg">
                        <div>（分享给好友和朋友圈的封面图，500*400）</div>
                        <!-- <el-input v-model="form.qyyxAcShareImg" placeholder="请输入活动分享图" /> -->
                        <el-upload :action="shareImgAction" :headers="uploadHeaders" :file-list="shareImg" list-type="picture-card" :on-success="handleUploadSuccShare">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                        <i class="el-icon-zoom-in"></i>
                                    </span>
                                    <span class="el-upload-list__item-delete" @click="handlePicRemove(file, shareImg)">
                                        <i class="el-icon-delete"></i>
                                    </span>
                                </span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="列表图片" prop="qyyxAcShareImg">
                        <div>（在活动列表显示，750*440）</div>
                        <!-- <el-input v-model="form.qyyxAcImg" placeholder="请输入活动分享图" /> -->
                        <el-upload :action="acImgActions" :headers="uploadHeaders" :file-list="acImg" list-type="picture-card" :on-success="handleUploadSuccAc">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                        <i class="el-icon-zoom-in"></i>
                                    </span>
                                    <span class="el-upload-list__item-delete" @click="handlePicRemove(file, acImg)">
                                        <i class="el-icon-delete"></i>
                                    </span>
                                </span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="活动内容" prop="qyyxAcContent"></el-form-item>
                </el-col>
            </el-row>
            <vue-ueditor-wrap class="editor"  v-model="form.qyyxAcContent" :config="editorConfig"></vue-ueditor-wrap>            
        </el-form>
        <el-dialog :visible.sync="showPicPreview">
            <img width="100%" :src="picPreviewUrl" alt="">
        </el-dialog>
        <div style="text-align: center;">
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
    </div>
</template>
<script>
    import requestCrm from '@/utils/requestCrm'
    import { getToken } from "@/utils/auth";
    import { getId } from "@/api/common"
    import { addActivity, updateActivity, getActivity } from "@/api/qyyx/activity";
    import { delFiles, getFileList } from "@/api/basic/file"
    import VueUeditorWrap from 'vue-ueditor-wrap'
    export default {
        name: "ActivityDetail",
        components: {
            VueUeditorWrap
        },
        data() {
            return {
                isNew:true,
                xq1Options:[],
                xq2Options:[],
                brandOptions:[],
                activityTypeOptions:[
                    {dictLabel:'否', dictValue:'0'},
                    {dictLabel:'是', dictValue:'1'}
                ],
                jlOptions:[
                    {dictLabel:'积分', dictValue:'1'},
                    {dictLabel:'现金', dictValue:'2'}
                ],
                form:{
                    qyyxAcXq1:undefined,
                    qyyxAcXq1Name:undefined,
                    qyyxAcXq2:undefined,
                    qyyxAcXq2Name:undefined,
                    qyyxAcPp:undefined,
                    qyyxAcPpName:undefined,
                    qyyxAcName:undefined,
                    qyyxAcHk:undefined,
                    qyyxAcHkType:undefined,
                    qyyxAcCj:undefined,
                    qyyxAcCjType:undefined,
                    qyyxAcKf:undefined,
                    qyyxAcContent:undefined,
                    lzjbYl1:undefined,
                    lzjbYl2:'0'
                },
                rules:{},
                uploadHeaders: {
                    Authorization: 'Bearer ' + this.$store.state.user.token,
                    lesseeId: this.$store.state.user.lesseeid
                },
                posterImgAction:'',
                shareImgAction:'',
                acImgActions:'',
                posterImg:[],
                shareImg:[],
                acImg:[],
                picPreviewUrl:'',
                showPicPreview:false,
                editorConfig:{
                    UEDITOR_HOME_URL: 'UEditor/',
                    // 服务器地址
                    serverUrl: process.env.VUE_APP_BASE_API,
                    //上传图片地址
                    uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload/news?sourcessId=&sourcessType=&sourcessType2=",
                    token: 'Bearer ' + getToken()
                }
            }
        },
        mounted(){
            let id = this.$route.params.id
            if(id!='new'){
                this.isNew = false
                this.form.id = id
                this.posterImgAction = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=ACTIVITY_INFO&sourcessType2=POSTER"
                this.shareImgAction = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=ACTIVITY_INFO&sourcessType2=SHARE"
                this.acImgActions = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=ACTIVITY_INFO&sourcessType2=AC"
                this.getXQ1Options(()=>{
                    this.getDetail(id)
                })
                this.getFileList(id, 'ACTIVITY_INFO', 'POSTER', (data)=>{
                    for(let i of data){
                        i.uid = i.id
                        i.url = i.fileFullUrl
                    }
                    this.posterImg = data
                })
                this.getFileList(id, 'ACTIVITY_INFO', 'SHARE', (data)=>{
                    for(let i of data){
                        i.uid = i.id
                        i.url = i.fileFullUrl
                    }
                    this.shareImg = data
                })
                this.getFileList(id, 'ACTIVITY_INFO', 'AC', (data)=>{
                    for(let i of data){
                        i.uid = i.id
                        i.url = i.fileFullUrl
                    }
                    this.acImg = data
                })
            }else{
                this.getXQ1Options()
                this.isNew = true
                this.createId(res =>{
                    this.form.id = res
                    this.posterImgAction = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+res+"&sourcessType=ACTIVITY_INFO&sourcessType2=POSTER"
                    this.shareImgAction = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+res+"&sourcessType=ACTIVITY_INFO&sourcessType2=SHARE"
                    this.acImgActions = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+res+"&sourcessType=ACTIVITY_INFO&sourcessType2=AC"
                })
            }
        },
        methods:{
            getDetail(id){
                getActivity(id).then(response => {
                    this.form = response.data
                    if(this.form.qyyxAcXq1){
                        this.getXQ2Options(this.form.qyyxAcXq1, ()=>{
                            if(this.form.qyyxAcXq2){
                                this.getBrandOptions(this.form.qyyxAcXq2)
                            }
                        })
                    }
                });
            },
            getFileList(id,sourcessType,sourcessType2,call){
                let params = {sourcessId:id,sourcessType,sourcessType2}
                getFileList(params).then(response => {
                    if (response.code === 200) {
                        if(call){
                            call(response.rows)
                        }
                    }
                })
            },
            createId(call){
                getId().then(response => {
                    if(call){
                        call(response.data.id)
                    }
                })
            },
            handleUploadSuccPoster(response, file, fileList){
                this.posterImg = fileList
            },
            handleUploadSuccShare(response, file, fileList){
                if(this.shareImg.length){
                    let fileId = this.shareImg[0].id || this.shareImg[0].response.fileId
                    delFiles({ids:fileId}).then(response => {})
                }
                file.id = response.fileId
                this.shareImg = [file]
            },
            handleUploadSuccAc(response, file, fileList){
                if(this.acImg.length){
                    let fileId = this.acImg[0].id || this.acImg[0].response.fileId
                    delFiles({ids:fileId}).then(response => {})
                }
                file.id = response.fileId
                this.acImg = [file]
            },
            handlePicPreview(file){
                this.picPreviewUrl = file.url
                this.showPicPreview = true
            },
            handlePicRemove(file, fileList){
                return this.$confirm('确定删除该图片?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let fileId = file.id||(file.response.fileId)
                    if(fileId){
                        delFiles({ids:fileId}).then(response => {
                            if (response.code !== 200) {
                                this.msgError(response.msg)
                            }else{
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                })
                                let findIndex = fileList.findIndex(obj=>{
                                    return obj.uid == file.uid
                                })
                                if(findIndex>=0){
                                    fileList.splice(findIndex,1)
                                }
                            }
                        })
                    }else{
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        let findIndex = fileList.findIndex(obj=>{
                            return obj.uid == file.uid
                        })
                        if(findIndex>=0){
                            fileList.splice(findIndex,1)
                        }
                    }
                }).catch((e) => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            getXQ1Options(call){
                requestCrm({
                    url:'WxService?method=getXQ1ByMemCode',
                    method: 'post',
                    data: {memCode:'HN029163'}
                }).then(res=>{
                    this.xq1Options = res.data
                    if(call){
                        call()
                    }
                })
            },
            getXQ2Options(xq1code, call){
                requestCrm({
                    url:'WxService?method=getXQ2ByMemCodeAndXQ1',
                    method: 'post',
                    data: {xq1code, memCode:'HN029163'}
                }).then(res=>{
                    this.xq2Options = res.data
                    if(call){
                        call()
                    }
                })
            },
            getBrandOptions(xq2Code, call){
                requestCrm({
                    url:'WxService?method=getBrandByMemCodeAndXQ2',
                    method: 'post',
                    data: {xq2Code, memCode:'HN029163'}
                }).then(res=>{
                    this.brandOptions = res.data
                    if(call){
                        call()
                    }
                })
            },
            onChangeXq1(e){
                let xq1 = this.xq1Options.find(obj=>{
                    return e == obj.RP02
                })
                if(xq1){
                    this.form.qyyxAcXq1Name = xq1.RP02NAME
                    this.form.qyyxAcXq2 = ''
                    this.form.qyyxAcXq2Name = ''
                    this.form.qyyxAcPp = ''
                    this.form.qyyxAcPpName = ''
                    this.xq2Options = []
                    this.brandOptions = []
                    this.getXQ2Options(xq1.RP02)
                }
            },
            onChangeXq2(e){
                let xq2 = this.xq2Options.find(obj=>{
                    return e == obj.RP03
                })
                if(xq2){
                    this.form.qyyxAcXq2Name = xq2.RP03NAME
                    this.form.qyyxAcPp = ''
                    this.form.qyyxAcPpName = ''
                    this.brandOptions = []
                    this.getBrandOptions(xq2.RP03)
                }
            },
            onChangeBrand(e){
                let brand = this.brandOptions.find(obj=>{
                    return e == obj.BRAND_CODE
                })
                if(brand){
                    this.form.qyyxAcPpName = brand.BRAND_NAME
                    this.form.lzjbYl2 = '0'
                }else{
                    this.form.lzjbYl2 = '0'
                }
            },
            submitForm(){
                if(this.shareImg.length){
                    this.form.qyyxAcShareImg = this.shareImg[0].url
                }
                if(this.acImg.length){
                    this.form.qyyxAcImg = this.acImg[0].url
                }
                
                // if((this.form.qyyxAcHkType=='1'||this.form.qyyxAcCj=='1')&&this.form.lzjbYl1){
                //     this.msgError('请填写MCU')
                //     return 
                // }else if(this.form.qyyxAcHkType=='2'&&this.form.qyyxAcCj=='2'){
                //     this.form.lzjbYl1 = undefined
                // }

                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (!this.isNew) {
                            updateActivity(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    this.$store.dispatch("tagsView/delView", this.$route).then(({ visitedViews }) => {
                                        this.$router.back()
                                    });
                                }
                            });
                        } else {
                            addActivity(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("新增成功");
                                    this.$store.dispatch("tagsView/delView", this.$route).then(({ visitedViews }) => {
                                        this.$router.back()
                                    });
                                }
                            });
                        }
                    }
                });
            }
        }
    }
</script>
<style scoped>
    .page-container{
        padding: 20px;
        display: block !important;;
        height: auto !important;
    }

    .page-container .editor{
        margin-bottom: 120px
    }

    /* .page-container .editor /deep/ .edui-editor{
        height: 700px
    } */
    #edui1 {
        height: 100%;
    }
</style>